# coding: utf-8
"""
refer:
https://my.oschina.net/u/4269090/blog/3329204
https://blog.csdn.net/qingshuiwater/article/details/82466544
https://blog.csdn.net/liu1121655792/article/details/88537568
"""
from alipay import AliPay
from urllib.parse import urlencode
from urllib.request import urlopen
from project.settings import alipay_settings

alipay_public_key_string = '''-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4n8oSRDOAr5PV5UPY85MbkZQ+rGNbWVl4P7WMjc1+Gesp6tncsEkTJ4j9oAdRNx3KvziXIcj8g+Sui3ZFW869xiHsq9UtptC9BBTH9XRJWfwXvf2ldXvx6dL5XwdXGsXbXzWtlnnWnw8Gd5es+m1yNoq5HNRLLbMREgg067EjvEO2ari/lhGmnjIm4z79Ci2jHr7Dm2Ox8rShIIfbGkhskwJUubf7AbrlRBh/ns82d9DMDC/xTtjnhc0fNCdlUqoZxMM9CQ5ZiEtOM6s56LADahc53YheipmU0Mlu1RqD0rBfb7H7XV8HtR3a9UGiw8WndfIUq+8nsd9G3BTuPrG0wIDAQAB
-----END PUBLIC KEY-----'''

app_private_key_string = '''-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAim0fE4J66qEoYtcdnWllb69yg8zAUiwihC3Fk5apE0ZrjJi0ztnlPQmtDSx6zP9fG+1vwA9rSADrwuqF1J3/iB9OZOYMEOt+5MrM2h7ezcj/8vt+kFqbg8MtQuhh9Qp3KHLPThBPndSNJqe5BH1uVekBbCkvhoxvern0PhR7nQwazKGIRYwicxFocsJW6adqKITM3Xbo6wcjER4JDPwLeFDxrZfNIbP0Rd69cZssSyRA9mkEugXhVUwrn8RZXO4clYFyR3qva14YM2GkxuEbIDM/IbEa1VL4TizD7XPJB75pYAzrXud8zYFTwWj09sV4/wXY6CjCOLPqbPJBDvy8BwIDAQABAoIBAGWTMQyF4GAvJY1xwF9zqWVM3sDsC+vASwum8qYcFbD5KY4ft/1ZUqd5ZCyYiPvIIChEEI5kQhqx4k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/jJF9M6J2XcFHKMDE3FqRXIjSMROdPjcVR+6KShL2RJ0ukdouGCOdVDjT90UX8ddLPvcOw==
-----END RSA PRIVATE KEY-----'''
# 注意：一个是支付宝公钥，一个是应用私钥


def init_alipay_cfg():
    """
    初始化alipay配置
    :return: alipay 对象
    """
    alipay = AliPay(
        appid=alipay_settings.APP_ID,
        app_notify_url=alipay_settings.ALIPAY_MOBILE_NOTIFY,  # 默认回调url
        app_private_key_string=app_private_key_string,
        alipay_public_key_string=alipay_public_key_string,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
        sign_type=alipay_settings.ALIPAY_MOBILE_SIGN_TYPE,  # RSA 或者 RSA2
        debug=False  # 默认False ,若开启则使用沙盒环境的支付宝公钥
    )
    return alipay


def app_pay(order_sn, total, subject):
    try:
        ali_pay = init_alipay_cfg()
        order_string = ali_pay.api_alipay_trade_app_pay(
            out_trade_no=order_sn,
            total_amount=total,
            subject=subject,  # 商品说明
        )
        return {"retcode": 0, "orderstring": order_string}
    except Exception as e:
        return {"retcode": 1, "msg": e}


# 手机h5支付
def wap_pay(order_sn, total, subject):
    try:
        ali_pay = init_alipay_cfg()
        order_string = ali_pay.api_alipay_trade_wap_pay(
            out_trade_no=order_sn,
            total_amount=total,
            subject=subject,  # 商品说明
            return_url=alipay_settings.ALIPAY_RETURN_URL
        )
        return {"retcode": 0, "orderstring": order_string}
    except Exception as e:
        return {"retcode": 1, "msg": e}


# PC网页支付
def page_pay(order_sn, total, subject):
    try:
        ali_pay = init_alipay_cfg()
        order_string = ali_pay.api_alipay_trade_page_pay(
            out_trade_no=order_sn,
            total_amount=total,
            subject=subject,  # 商品说明
        )
        return {"retcode": 0, "orderstring": order_string}
    except Exception as e:
        return {"retcode": 1, "msg": e}


def notify_verify(post_querydict):
    """
    <QueryDict: {'gmt_create': ['2021-01-27 14:54:49'], 'charset': ['utf-8'], 'seller_email': ['momself@qq.com'],
    'subject': ['365天超级会员'], 'sign': ['YLx/63QpgrnxvS6Wt+Ky24NWSapsvzm9p3S2Jur7EPZvO2r7vrTtywMRs3EGPhiBjpeNH0PWlbL
    lXmy8LuxR0X9m2hKxzbOUK7fab3nBPa/pDIAEAz/wibR29w3uSwLMzCYvgprNhn5HtYQ/fAozzSlfofkdcZUbm+qpYJXrnnrMbT7V1fAwK9EuOIV
    93QOzG6987Prcjbm2LijGnC9eSVx9mS0If/SJXNhR15/oDf6czWHrsT8bGVit5MrH5HYaVH1r/g+oyR0pX6HzLaF4qc7zlnyTH9JmRL3fE4Vq09Y
    baFsqbwJtV0c3VKcxEST8deDJdVY+6Waa34JcTXuEow=='], 'buyer_id': ['2088012116067152'], 'invoice_amount': ['0.01'],
    'notify_id': ['2021012700222145450067151458737487'], 'fund_bill_list': ['[{"amount":"0.01",
    "fundChannel":"PCREDIT"}]'], 'notify_type': ['trade_status_sync'], 'trade_status': ['TRADE_SUCCESS'],
    'receipt_amount': ['0.01'], 'app_id': ['2021001152647049'], 'buyer_pay_amount': ['0.01'], 'sign_type': ['RSA2'],
    'seller_id': ['2088521507106405'], 'gmt_payment': ['2021-01-27 14:54:50'], 'notify_time': ['2021-01-27 14:54:51'],
    'version': ['1.0'], 'out_trade_no': ['7_1611730482_1_1_1'], 'total_amount': ['0.01'], 'trade_no':
    ['2021012722001467151440333478'], 'auth_app_id': ['2021001152647049'], 'buyer_logon_id': ['137****7066'],
    'point_amount': ['0.00']}>
    :param post_querydict:
    :return:
    """
    post = {}
    for key, value in post_querydict.items():
        post[key] = value
    # 初级验证--签名
    signature = post.pop("sign")
    # 检查签名
    ali_pay = init_alipay_cfg()
    if not ali_pay.verify(post, signature):
        return False

    # 二级验证--查询支付宝服务器此条信息是否有效
    params = {'partner': alipay_settings.ALIPAY_PARTNER, 'notify_id': post.get('notify_id')}
    if alipay_settings.ALIPAY_TRANSPORT == 'https':
        params['service'] = 'notify_verify'
        gateway = 'https://mapi.alipay.com/gateway.do'
    else:
        gateway = 'http://notify.alipay.com/trade/notify_query.do'
    veryfy_result = urlopen(gateway, urlencode(params).encode('utf-8')).read().decode('utf-8')  # py3 str不支持
    if veryfy_result.lower().strip() == 'true':
        return True

    print('verify result no true!!')
    return False
